from typing import Union

from rest_framework.request import Request
from rest_framework.response import Response

from .utils import dump_md5


def etag_json(data: Union[dict, list], request: Request, status: int = 209):
    """response with etag and check if match"""
    if (etag := dump_md5(data)) == (
        etag_from_params := request.query_params.get("etag")
    ):
        return Response({}, status)
    headers = {"Access-Control-Expose-Headers": "Etag", "Etag": etag}
    if etag_from_params is not None:
        data = dict(data=data, etag=etag)
    return Response(data, headers=headers)
